package com.daka.controller;

import com.daka.annotation.Login;
import com.daka.entity.User;
import com.daka.enumerate.DictionaryMap;
import com.daka.enumerate.StatusCode;
import com.daka.service.UserService;
import com.daka.tools.CheckLogin;
import com.daka.tools.MD5Util;
import com.daka.vo.request.ResetPasswordVo;
import com.daka.vo.request.UserPageRequestVo;
import com.daka.vo.request.UserRegisterRequestVo;
import com.daka.vo.response.BaseResponseVo;
import com.daka.vo.response.DataResponseVo;
import com.daka.vo.response.ListDataResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;


/**
 * @author beliveli on 2016/3/31 0031.
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource(name = "userService")
    private UserService userService;

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/list", consumes = "application/json")
    @Login
    public ListDataResponseVo list(@Valid @RequestBody UserPageRequestVo userParam,HttpSession session) {

        List<Integer> competenceList = new ArrayList<Integer>();
        competenceList.add(DictionaryMap.SYSTEM.getStatusCode());
        if (!CheckLogin.checkRole(session, competenceList)) {
            return new ListDataResponseVo<User>(StatusCode.NO_COMPETENCE.getStatusCode(), StatusCode.NO_COMPETENCE.getStatusMessage());
        }

        List<User> userList = userService.selectByParam(userParam.getRoleId(),userParam.getKey());
        return new ListDataResponseVo<User>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), userList);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/info", consumes = "application/json")
    public DataResponseVo info(@Valid @RequestBody UserPageRequestVo userParam) {
        User user = userService.selectById(userParam.getUserId());
        return new DataResponseVo<User>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), user);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/login", consumes = "application/json")
    public DataResponseVo<User> login(@Valid @RequestBody User userParam, HttpSession session) {
        DataResponseVo<User> result = userService.login(userParam);
        if (result != null && result.getStatusCode() == StatusCode.SUCCESS.getStatusCode()) {
            session.setAttribute("userId", result.getData().getManageId());
            session.setAttribute("roles", result.getData().getRoles());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/register", consumes = "application/json")
    public DataResponseVo<User> register(@Valid @RequestBody User userParam) {

        User checkExists = userService.selectByPhone(userParam.getPhone());
        if (checkExists != null) {
            return new DataResponseVo<User>(StatusCode.ADD_ERROR.getStatusCode(), "手机号已存在");
        }

        User result = userService.saveUser(userParam);
        if (result == null) {
            return new DataResponseVo<User>(StatusCode.ADD_ERROR.getStatusCode(), "服务器异常，请联系系统管理员");
        }

        return new DataResponseVo<User>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), result);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/edit", consumes = "application/json")
    @Login
    public DataResponseVo<User> edit(@Valid @RequestBody User userParam, HttpSession session) {

        List<Integer> competenceList = new ArrayList<Integer>();
        competenceList.add(DictionaryMap.SYSTEM.getStatusCode());
        //noinspection EqualsBetweenInconvertibleTypes
        if (!CheckLogin.checkRole(session, competenceList) || session.getAttribute("userId").toString().equals(userParam.getManageId())) {
            return new DataResponseVo<User>(StatusCode.NO_COMPETENCE.getStatusCode(), StatusCode.NO_COMPETENCE.getStatusMessage());
        }

        return userService.updateUser(userParam);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/changePassword", consumes = "application/json")
    @Login
    public DataResponseVo<User> changePassword(@Valid @RequestBody UserRegisterRequestVo userParam, HttpSession session) {

        List<Integer> competenceList = new ArrayList<Integer>();
        competenceList.add(DictionaryMap.SYSTEM.getStatusCode());
        //noinspection EqualsBetweenInconvertibleTypes
        if (!CheckLogin.checkRole(session, competenceList) || session.getAttribute("userId").toString().equals(userParam.getManageId())) {
            return new DataResponseVo<User>(StatusCode.NO_COMPETENCE.getStatusCode(), StatusCode.NO_COMPETENCE.getStatusMessage());
        }

        User user = userService.selectById(userParam.getManageId());
        if (!user.getPassword().equalsIgnoreCase(MD5Util.MD5(userParam.getOldPassword()))) {
            return new DataResponseVo<User>(StatusCode.USER_PASSWORD_ERROR.getStatusCode(), StatusCode.USER_PASSWORD_ERROR.getStatusMessage());
        }
        user.setPassword(userParam.getNewPassword());
        return userService.updateUser(user);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/sendCode", consumes = "application/json")
    public BaseResponseVo sendCode(@Valid @RequestBody ResetPasswordVo resetPasswordVo) {

        User user = userService.selectByPhone(resetPasswordVo.getPhone());
        if (user == null) {
            return new BaseResponseVo(StatusCode.SELECT_ITEM_NOT_EXISTS.getStatusCode(), StatusCode.SELECT_ITEM_NOT_EXISTS.getStatusMessage());
        }
        String code = userService.sendVerifierCode(resetPasswordVo.getPhone());
        if (code.length() > 0) {
            return new BaseResponseVo(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage());
        }
        return new BaseResponseVo(StatusCode.SEND_CODE_ERROR.getStatusCode(), StatusCode.SEND_CODE_ERROR.getStatusMessage());
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/resetPassword", consumes = "application/json")
    public BaseResponseVo resetPassword(@Valid @RequestBody ResetPasswordVo resetPasswordVo) {

        boolean flag = userService.checkVerifierCode(resetPasswordVo.getPhone(), resetPasswordVo.getCode());
        if (flag) {
            User user = userService.selectByPhone(resetPasswordVo.getPhone());
            user.setPassword(MD5Util.MD5(resetPasswordVo.getPassword()));
            int resultCount = userService.updatePasswordById(user);
            if (resultCount == 0) {
                return new BaseResponseVo(StatusCode.ADD_ERROR.getStatusCode(), StatusCode.ADD_ERROR.getStatusMessage());
            }
            return new BaseResponseVo(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage());
        }
        return new BaseResponseVo(StatusCode.RESET_ERROR.getStatusCode(), StatusCode.RESET_ERROR.getStatusMessage());
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/test", consumes = "application/json")
    public DataResponseVo<User> test(@Valid @RequestBody User userParam) {
        return new DataResponseVo<User>(0, "", userService.selectByPhone(userParam.getPhone()));
    }
}
